'use strict'

import React, { Component } from 'react'
import noop from 'lodash/noop'

import './style.scss'

const drawerFallingAnimation = {
    WebkitAnimation: 'fall 0.4s 1 ease'
}

export default class Drawer extends Component {
    constructor(props) {
        super(props)
        this.state = {
            open: this.props.open,
            destroy: true
        }
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.open) {
            this.build()
        } else {
            this.dismiss()
        }
    }

    build() {
        this.setState({
            open: true,
            destroy: false
        })
    }

    destroy() {
        this.setState({
            destroy: true
        })
    }

    dismiss() {
        this.setState({
            open: false
        })
        this.props.onDismiss()
        setTimeout(() => {
            this.destroy()
        }, 400)
    }

    render() {
        return this.state.destroy
            ? null
            : (
            <div className="ddui-drawer">
                <div className="drawer" style={!this.state.open ? drawerFallingAnimation : null}>
                    {this.props.children}
                </div>
                {this.state.open ? <div onClick={this.dismiss.bind(this)} className="backdrop"/> : null}
            </div>
        )
    }
}

Drawer.defaultProps = {
    open: true,
    onDismiss: noop
}

Drawer.propTypes = {
    open: React.PropTypes.bool,
    onDismiss: React.PropTypes.func
}